#include <thirdparty/fist-log.h>
#include "db_conf.h"
#include "db_info.h"

CDBConfParser::CDBConfParser()
        : m_conf(new DBConf())
{

}

CDBConfParser::~CDBConfParser()
{
    delete m_conf;
}

bool CDBConfParser::Parser(XMLElement *root)
{
    m_conf->connectKeys.clear();
    auto db = root->FirstChildElement("db")->FirstChildElement();
    while (db) {
        auto host = db->FindAttribute("host");
        if (host == nullptr) {
            return false;
        }

        auto username = db->FindAttribute("username");
        auto password = db->FindAttribute("password");
        auto database = db->FindAttribute("database");
        if ((username == nullptr || password == nullptr) && database == nullptr) {
            LOG_ERROR("db config error. please check file!");
            return false;
        }
        DBConnectKey connectKey;
        connectKey.host = host->Value();
        if (username && password) {
            connectKey.username = username->Value();
            connectKey.password = password->Value();
        }
        if (database) {
            connectKey.database = database->Value();
        }
        auto port = db->FindAttribute("port");
        if (port) {
            connectKey.port = port->UnsignedValue();
        }
        m_conf->connectKeys.emplace_back(connectKey);
        db = db->NextSiblingElement();
    }
    return true;
}

const DBConf *CDBConfParser::conf()
{
    return m_conf;
}


